﻿@using TaskoMask.BuildingBlocks.Contracts.Dtos.Owners
@inject OwnerApiService OwnerApiService

<EditForm id="user_update_profile_form" Model="OwnerUpdateModel" OnValidSubmit="HandleUpdateOwner">

    <DataAnnotationsValidator />
    <input id="user_profile_email" type="hidden" value="@OwnerUpdateModel.Email" />
    <input id="user_profile_displayname" type="hidden" value="@OwnerUpdateModel.DisplayName" />

    <div class="form-group">
        <InputText @bind-Value="OwnerUpdateModel.DisplayName" placeholder="Display Name" class="form-control"></InputText>
        <ValidationMessage For="()=>OwnerUpdateModel.DisplayName" class="text-danger"></ValidationMessage>
    </div>

    <div class="form-group">
        <InputText @bind-Value="OwnerUpdateModel.Email" placeholder="Email" class="form-control"></InputText>
        <ValidationMessage For="()=>OwnerUpdateModel.Email" class="text-danger"></ValidationMessage>
    </div>



    <div class="form-group">
        <button type="submit" class="btn btn-primary mr-1">Update</button>

        <button @onclick="@(()=>ModalInstance.CancelAsync())" class="btn btn-warning text-dark mr-1">Cancel</button>
    </div>

</EditForm>

@code {

    #region Fields and Parameters



    /// <summary>
    /// Form Model
    /// </summary>
    UpdateOwnerProfileDto OwnerUpdateModel = new UpdateOwnerProfileDto();



    /// <summary>
    /// Access to current modal
    /// </summary>
    [CascadingParameter]
    BlazoredModalInstance ModalInstance { get; set; }




    #endregion Fields and Parameters


    #region Protected Methods


    /// <summary>
    ///
    /// </summary>
    protected override async Task OnInitializedAsync()
    {
        var ownerResult = await OwnerApiService.GetAsync();

        if (ownerResult.IsSuccess)
        {
            OwnerUpdateModel = new UpdateOwnerProfileDto
                {
                    Id = ownerResult.Value.Id,
                    DisplayName = ownerResult.Value.DisplayName,
                    Email = ownerResult.Value.Email,
                };

        }
        else
        {
            QueryResultHandler<GetOwnerDto>.Init()
                .WithResult(ownerResult)
                .ShowErrorToast(ToastService)
                .CloseModal(ModalInstance);
        }
    }


    #endregion Protected Methods



    #region private Methods



    /// <summary>
    /// Handle form role
    /// </summary>
    private async Task HandleUpdateOwner()
    {
        var result = await OwnerApiService.UpdateProfileAsync(OwnerUpdateModel);
        CommandResultHandler.Init()
            .WithResult(result)
            .WithComponentMessageType(MessageType.Owner_Updated)
            .ShowErrorToast(ToastService)
            .PublishMessage(ComponentMessageService)
            .CloseModal(ModalInstance);
    }



    #endregion private Methods

}